﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Universum.Infrastructure.Persistence;
using Universum.Infrastructure.Persistence.Queries.Resource;
using System.Security.Principal;
using System.IO;
using Universum.Infrastructure.Configuration;
using Universum.Model.Domain;
using Universum.Infrastructure.Persistence.Queries.User;

namespace Universum.Model.Services.Personals
{
	public class PersonalServiceImpl : IPersonalService
	{
		IRepository _Repository;
		IPrincipal _Principal;
		public PersonalServiceImpl(
			IPrincipal principal,
			IRepository
			repository)
		{
			_Repository = repository;
			_Principal = principal;
		}
		#region IPersonalService Members

		public bool HasPicture
		{
			get
			{
				return
					null != _Repository.Query(new ResourceByOwnerAndPath(_Principal.Identity.Name, get_path_for_user_photo())).FirstOrDefault();
			}
		}

		private string get_path_for_user_photo()
		{
			return Path.Combine(ConstantIdentifiers.USER_PICTURE_PATH,
				_Principal.Identity.Name);
		}

		#endregion

		#region IPersonalService Members



		public Universum.Model.Domain.Resource GetPicture()
		{
			var picture = _Repository.Query(new ResourceByOwnerAndPath(_Principal.Identity.Name, get_path_for_user_photo())).FirstOrDefault();

			return
				picture;
		}

		#endregion

		#region IPersonalService Members


		public Resource SaveOrUpdateUserPicture(HttpPostedFileBase newPicture)
		{
			var Picture =
			_Repository.Query(new ResourceByOwnerAndPath(_Principal.Identity.Name, get_path_for_user_photo())).FirstOrDefault()
			?? // if the thing is null suplly some values
			new Resource
			{
				ContentLength = newPicture.ContentLength,
				ContentType = newPicture.ContentType,
				FileName = newPicture.FileName,
				Owner = _Principal.Identity.Name,
				Path = get_path_for_user_photo(),
				ID = Guid.NewGuid()
			};

			
			_Repository.SaveOrUpdate(Picture);
			return Picture;
		}

		#endregion

		#region IPersonalService Members


		public void SaveOrUpdateUserDescription(string description)
		{
			var userDetails = _Repository.Query(new PersonalDetailsByUsername(_Principal.Identity.Name)).FirstOrDefault()
				??
				new PersonalDetails
				{
					ID = Guid.NewGuid(),
					
					Username = _Principal.Identity.Name
				}
				;
			description = description.Trim();
			userDetails.Description = (description.Length > 140) ? description.Substring(0,140): description;
			_Repository.SaveOrUpdate(userDetails);
	
		}
		const string SUPPLY_A_DESCRIPTION = "Enter your description";
		public string GetUserDescription()
		{
			var userDetails = _Repository.Query(new PersonalDetailsByUsername(_Principal.Identity.Name)).FirstOrDefault()
				;
			if (userDetails == null)
				return SUPPLY_A_DESCRIPTION;
			else
				return userDetails.Description;
		}

		#endregion
	}
}
